<template>
  <el-container class="map-container">
    <el-header class="map-toolbar">
      <el-row :gutter="10" align="middle" style="width: 100%">
        <el-col :span="4">
          <div class="city-display">{{ city }}</div>
        </el-col>

        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索省级行政区 (如: 北京市)"
            style="width: 240px"
            size="large"
            :prefix-icon="Search"
            @keyup.enter="handleSearchCity"
          ></el-input>
        </el-col>

        <el-col :span="6">
          <el-select
            v-model="drawType"
            placeholder="请选择绘制图形"
            clearable
            @change="handleDrawType"
          >
            <el-option
              v-for="item in option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-select v-model="markerType" placeholder="选择标记" clearable>
            <el-option label="标记 1" value="marker_1" />
            <el-option label="标记 2" value="marker_2" />
          </el-select>
        </el-col>
      </el-row>
    </el-header>

    <el-main class="map-content">
      <div id="map" ref="mapContainer"></div>
      <div id="popup" ref="popupElement" v-html="popupContent"></div> 
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import {
  ElHeader,
  ElMain,
  ElContainer,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElInput,
} from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import 'ol/ol.css'; 

import { getCityByIp, getGeocodeByCity } from '@/api/map';

import { MapManager } from '../src/utils/mapTools';


const mapContainer = ref<HTMLElement | null>(null);
const popupElement = ref<HTMLElement | null>(null);
const city = ref('');
const searchQuery = ref('');
const drawType = ref<'line' | 'circle' | 'polygon' | 'freehand' | 'clear' | ''>('');
const markerType = ref('');
const adcode = ref('');
const cityLocation = ref<number[]>([]);
const popupContent = ref('');
const option = [
  { label: '直线', value: 'line' as const },
  { label: '圆形', value: 'circle' as const },
  { label: '多边形', value: 'polygon' as const },
  { label: '自由笔画', value: 'freehand' as const },
  { label: '清除绘图', value: 'clear' as const },
];
let mapManager: MapManager | null = null; 

/**
 * OpenLayers 事件回调：更新组件状态
 */
const updatePopupContent = (content: string, position: number[] | undefined) => {
    popupContent.value = content;
};

/**
 * 初始化地图
 */
const initMap = async () => {
  if (!mapContainer.value || !popupElement.value) return;

  mapManager = new MapManager();

  mapManager.initializeMap(
    mapContainer.value,
    popupElement.value,
    updatePopupContent
  );

  mapManager.registerZoomListener();

  const ipCityRes = await getCityByIp();
  city.value = ipCityRes.city;
  adcode.value = ipCityRes.adcode;

  const geocodeRes = await getGeocodeByCity(city.value);
  cityLocation.value = geocodeRes.geocodes[0].location.split(',').map(Number);

  setTimeout(() => {
    mapManager?.addCityBoundary(adcode.value, cityLocation.value);
  }, 1000);
};

/**
 * 处理绘图类型变更
 */
const handleDrawType = () => {
  if (mapManager) {
    mapManager.toggleDrawInteraction(drawType.value);
  }
  if (drawType.value === 'clear') {
    drawType.value = '';
  }
};

/**
 * 处理城市搜索
 */
const handleSearchCity = async () => {
  if (!searchQuery.value.trim() || !mapManager) return;

  const searchCityName = searchQuery.value;

  // 搜索城市地理信息
  const res = await getGeocodeByCity(searchCityName);
  if (res.status === '0' || res.geocodes.length === 0) {
    searchQuery.value = '';
    alert('未找到该城市');
    return;
  }

  // 更新城市信息并添加新图层
  adcode.value = res.geocodes[0].adcode;
  cityLocation.value = res.geocodes[0].location.split(',').map(Number);
  
  mapManager.addCityBoundary(adcode.value, cityLocation.value);

  // 清空搜索框
  searchQuery.value = '';
};

// 组件挂载时初始化地图
onMounted(() => {
  initMap();
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.map-toolbar {
  background-color: #007bff;
  color: white;
  padding: 0 20px;
  height: 60px;
  display: flex;
  align-items: center;
}

.city-display {
  font-size: 1.2rem;
  font-weight: bold;
}

.map-content {
  padding: 0;
  flex-grow: 1;
  position: relative;
}

#map {
  width: 100%;
  height: 100%;
}

#popup {
  width: 200px;
  height: max-content;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  background-color: pink;
}

/* 隐藏空的 popup */
#popup:empty {
  display: none;
}

/* 工具栏组件样式覆盖 */
.map-toolbar :deep(.el-autocomplete),
.map-toolbar :deep(.el-select),
.map-toolbar :deep(.el-input) {
  width: 100%;
  --el-fill-color-blank: rgba(255, 255, 255, 0.9);
  --el-text-color-regular: #333;
}
</style>